//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { NodeEditPanelProps } from './common';
import { Button, Card, Form, Input, List, Modal, Radio, Space } from 'antd';
import { useRoadmapStores } from '../../store';
import { update_node_data } from "@/api/roadmap_content";
import { request } from '@/utils/request';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
import type { RoadmapInfo } from "@/api/roadmap";
import { list_pub } from "@/api/roadmap";

const PAGE_SIZE = 10;

interface EditModalProps {
    targetId: string;
    targetTitle: string;
    onCancel: () => void;
    onOk: (newTargetId: string, newTargetTitle: string) => void;
}

const EditModal = observer((props: EditModalProps) => {
    const roadmapStore = useRoadmapStores();

    const [targetId, setTargetId] = useState(props.targetId);
    const [targetTitle, setTargetTitle] = useState(props.targetTitle);

    const [totalCount, setTotalCount] = useState(0);
    const [roadmapList, setRoadmapList] = useState<RoadmapInfo[]>([]);
    const [curPage, setCurPage] = useState(0);
    const [keyword, setKeyword] = useState("");

    const loadRoadmapList = async () => {
        const res = await request(list_pub({
            session_id: roadmapStore.sessionId,
            filter_by_keyword: keyword != "",
            keyword: keyword,
            filter_by_tag: false,
            tag: "",
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setTotalCount(res.total_count);
        setRoadmapList(res.roadmap_list);
    };

    useEffect(() => {
        loadRoadmapList();
    }, [curPage, keyword]);

    return (
        <Modal open mask={false} bodyStyle={{ padding: "0px 0px" }}
            okText="设置" okButtonProps={{ disabled: props.targetId == targetId || targetId == "" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onOk(targetId, targetTitle);
            }}>
            <Card title="选择路线图" bordered={false} bodyStyle={{ maxHeight: "calc(100vh - 300px)", overflowY: "scroll" }}
                extra={
                    <Form layout='inline' style={{ marginRight: "20px" }}>
                        <Form.Item>
                            <Input placeholder='请输入关键词' value={keyword}
                                onChange={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setCurPage(0);
                                    setKeyword(e.target.value.trim());
                                }} />
                        </Form.Item>
                    </Form>
                }>
                <List rowKey="roadmap_id" dataSource={roadmapList}
                    pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), showSizeChanger: false }}
                    renderItem={roadmapItem => (
                        <List.Item>
                            <Space>
                                <Radio checked={roadmapItem.roadmap_id == targetId} onChange={e => {
                                    e.stopPropagation();
                                    if (e.target.checked) {
                                        setTargetId(roadmapItem.roadmap_id);
                                        setTargetTitle(roadmapItem.basic_info.title);
                                    }
                                }}>{roadmapItem.basic_info.title}</Radio>
                            </Space>
                        </List.Item>
                    )} />
            </Card>
        </Modal>
    );
});

const RoadmapRefNodeEditPanel = (props: NodeEditPanelProps) => {
    const roadmapStore = useRoadmapStores();

    const [targetId, setTargetId] = useState("");
    const [targetTitle, setTargetTitle] = useState("");
    const [showModal, setShowModal] = useState(false);

    const reset = () => {
        const curNode = roadmapStore.getNode(props.nodeId);
        if (curNode == undefined) {
            return;
        }
        setTargetId(curNode.basic_info.node_data.RoadmapRefData?.target_id ?? "");
        setTargetTitle(curNode.basic_info.node_data.RoadmapRefData?.target_title ?? "");
    };

    const updateNodeData = async (newTargetId: string, newTargetTitle: string) => {
        await request(update_node_data({
            session_id: roadmapStore.sessionId,
            roadmap_id: roadmapStore.roadmapId,
            node_id: props.nodeId,
            node_data: {
                RoadmapRefData: {
                    target_id: newTargetId,
                    target_title: newTargetTitle,
                },
            },
        }));
        setShowModal(false);
        await roadmapStore.onUpdateNode(props.nodeId);
        await reset();
    };

    useEffect(() => {
        reset();
    }, []);

    return (
        <div>
            <Button type='primary' danger
                style={{ position: "fixed", top: "10px", right: "20px" }} icon={<DeleteOutlined />}
                onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    roadmapStore.removeNode(props.nodeId);
                }}>删除</Button>
            <Form>
                <Form.Item label="引用路线图">
                    <Space>
                        <span>{targetTitle}</span>
                        <Button type="link" icon={<EditOutlined />} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setShowModal(true);
                        }} />
                    </Space>
                </Form.Item>
            </Form>
            {showModal == true && (
                <EditModal targetId={targetId} targetTitle={targetTitle} onCancel={() => setShowModal(false)}
                    onOk={(newTargetId, newTargetTitle) => updateNodeData(newTargetId, newTargetTitle)} />
            )}
        </div>
    );
};

export default observer(RoadmapRefNodeEditPanel);